package kaalanshare;

import java.io.File;
import java.io.IOException;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * User: twin
 * Date: 21.04.12
 * Time: 23:04
 * To change this template use File | Settings | File Templates.
 */
public class Main {
    static FolderStructure folder = null;
    volatile static boolean stop = false;

    public static void main(String[] args) throws IOException {

        // Server for handling incoming requests for files and folders
        ServerRunnable serv = new ServerRunnable();
        Thread servThread = new Thread(serv);
        servThread.start();

        // Checks shared folder for changes
        Thread folderUpdater = new Thread(new Runnable() {
            @Override
            public void run() {
                while (Main.stop != true) {
                    synchronized (Main.class) {
                        folder = new FolderStructure(new File("share"));
                    }
                    long numMillisecondsToSleep = 4000;
                    try {
                        Thread.sleep(numMillisecondsToSleep);
                        System.out.println("updated");
                    } catch (InterruptedException e) {
                        System.out.println("Folder updater finished");
                        //e.printStackTrace();
                    }
                }
            }
        });
        folderUpdater.start();

        // Broadcasts the structure of shared folder
        Thread folderBroadcaster = new Thread(new Runnable() {
            @Override
            public void run() {
                while (Main.stop != true) {
                    synchronized (Main.class) {
                        if (folder != null)
                            folder.broadcastFolder();
                    }
                    long numMillisecondsToSleep = 2000;
                    try {
                        Thread.sleep(numMillisecondsToSleep);
                        System.out.println("sent");
                    } catch (InterruptedException e) {
                        System.out.println("Folder broadcaster finished");
                    }
                }
            }
        });
        folderBroadcaster.start();

        //Server will exit on keypressed
        new Scanner(System.in).nextLine();
        Main.stop=true;
        serv.stop = true;
        serv.servsock.close();
        folderBroadcaster.interrupt();
        folderUpdater.interrupt();

        try {
            servThread.join();
            folderBroadcaster.join();
            folderUpdater.join();
        } catch (InterruptedException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
    }
}
